{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Python介绍\n",
    "python是一门动态解释型的强类型定义语言。它的开发效率非常高，有非常强大的第三方库，基本上你想通过计算机实现任何功能，Python官方库里都有相应的模块进行支持，直接下载调用后，在基础库的基础上再进行开发，大大降低开发周期，避免重复造轮子。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello world\n"
     ]
    }
   ],
   "source": [
    "print(\"hello world\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 了解IDLE窗口\n",
    "IDLE是python自带代码编辑器，IDE是程序员的一个编辑器。如果要将代码保存到文件中，请转到“文件”菜单并选择“新建窗口”（或按ctrl+n）。现在您可以输入程序并将其保存在此处。使用python shell的主要好处是，在将代码放入真正的程序之前，您可以用小片段进行试验，以了解代码的行为。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 函数+模块=标准库 \n",
    "#### 标准库、开源模块和自定义模块\n",
    "- 相关函数的一个集合构成了一个模块，标准库中有大量模块；系统自带了一些方便我们使用的方法，他们统称标准库。\n",
    "- 开源模块指可修改的模块。\n",
    "- 自定义模块指可自己定义的模块，是在主模块基础上自己更改的。\n",
    "#### 模块\n",
    "- sys模块可以帮助了解运行解释器的系统\n",
    "- platform属性为访问预置属\n",
    "- os模块可提供功能\n",
    "- environ属性为系统的全部环境变量\n",
    "- getenv函数为某一环境变量\n",
    "- datetime模块可处理日期（和时间）\n",
    "- date.today函数提供当天日期\n",
    "- date.isoformat函数可将日期转换成字符串\n",
    "- 导入time模块，调用strftime函数可处理时间，例如24小时制形式\n",
    "- if是表条件，else则表示其指示所对应的if语句返回False值时则执行else的代码块。 elif后面的命令是根据上一个if是否运行，如果运行了，elif则略过，否则才运行。\n",
    "- 代码块：一个模块，一个函数，一个类，一个文件等都是一个代码块。\n",
    "- 迭代是重复反馈过程的活动，其目的通常是为了逼近所需目标或结果。 每一次对过程的重复称为一次“迭代”，而每一次迭代得到的结果会作为下一次迭代的初始值。\n",
    "- for循环迭代处理序列，还可以更准确地指定迭代次数。 range最基本的形式是接收一个整数参数，指示for循环要运行多少次。\n",
    "- ......\n",
    "\n",
    "#### 标准库\n",
    "- 时间模块：time与datetime\n",
    "\n",
    "- 在Python中，通常有这几种方式来表示时间：\n",
    "\n",
    "```python\n",
    "import time\n",
    "time.time()\n",
    "```\n",
    "\n",
    "- 格式化的时间字符串\n",
    "\n",
    "按照自己等格式定义的字符串例如：（2019-08-25 08:30:56）等\n",
    "\n",
    "- 元组（struct_time）共九个元素。由于Python的time模块实现主要调用C库，所以各个平台可能有所不同。\n",
    "\n",
    "- Python的标准库非常广泛，可提供各种功能\n",
    "\n",
    "##### help的使用\n",
    "\n",
    "```python\n",
    "import time\n",
    "help(time)\n",
    "\n",
    "import time\n",
    "time.localtime()\n",
    "\n",
    "import time\n",
    "time.sleep(2)\n",
    "\n",
    "import time  #转换成UTC\n",
    "help(time.gmtime)\n",
    "time.gmtime()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 变量、赋值、数据\n",
    " 变量用于存储要在计算机程序中引用和操作的信息。它们还提供了一种用描述性名称标记数据的方法，以便读者和我们自己能够更清楚地理解我们的程序。将变量看作包含信息的容器是有帮助的。它们的唯一目的是在内存中标记和存储数据。然后可以在整个程序中使用这些数据。\n",
    " \n",
    " **声明变量**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#_*_coding:utf-8_*_\n",
    "name =\"Wu Xiaoyan\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*上述代码声明了一个变量，变量名为： name，变量name的值为：\"Wu Xiaoyan\"*\n",
    "\n",
    "**变量定义的规则：**\n",
    "- 变量名只能是 字母、数字或下划线的任意组合\n",
    "- 变量名的第一个字符不能是数字\n",
    "- 以下关键字不能声明为变量名\n",
    "['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda','not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']\n",
    "\n",
    "**变量的命名（补充）：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "wait_time = 26\n",
    "gf_of_liu = \"Lucy\" #_类型，比较常用的类型\n",
    "GFOfLiu = \"Lucy\" #首字母大写"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*错误的例子：*\n",
    "```python\n",
    "2age = 18\n",
    "and = \"true\"\n",
    "$name =\"James\"\n",
    "4gender is = \"male\"\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**变量的赋值：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Xiaoyan Xiaoyan\n",
      "What is the value of name2 now?\n"
     ]
    }
   ],
   "source": [
    "name = \"Xiaoyan\"\n",
    "\n",
    "name2 = name\n",
    "print(name,name2)\n",
    "\n",
    "name = \"Xiaoming\"\n",
    "\n",
    "print(\"What is the value of name2 now?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 项目1\n",
    "```python\n",
    "from datetime import datetime\n",
    "\n",
    "odds = [  1, 3,  5,  7,  9, 11,13,15,17,19\n",
    "             21,23,25,27,29,31,33,35,37,39\n",
    "             41,43,45,47,49,51,53,55,57,59]\n",
    "\n",
    "right_this_minute = datetime.today().minute\n",
    "\n",
    "if right_this_minute in odds:\n",
    "    print(\"This minute seems a little odd.\")\n",
    "else:\n",
    "    print(\"Not an odd minute.\")\n",
    "```\n",
    "\n",
    "**if语句**\n",
    "```python\n",
    "\n",
    "   if 条件:\n",
    "      if-语句块\n",
    "   \n",
    "   if 条件:\n",
    "      if-语句块\n",
    "   else:\n",
    "      else-语句块\n",
    "   \n",
    "   if 条件：\n",
    "      if-语句块\n",
    "   elif 条件:\n",
    "      elif-语句块\n",
    "   ...\n",
    "   else:\n",
    "      else-语句块\n",
    "   可以进行嵌套。 不要超过3层， 最多5层\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 循环嵌套\n",
    "```python\n",
    "if today == \"Saturday\":\n",
    "    print(\"Party!\")\n",
    "elif today == \"Sunday\":\n",
    "    if condition == \"Headache\":\n",
    "        print(\"Recover, then rest.\")\n",
    "    else:\n",
    "        print(\"Rest.\")\n",
    "else:\n",
    "    print(\"Work, work, work.\")\n",
    "```\n",
    "**练习if elif**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "星期几：三\n",
      "小时：18\n",
      "分钟：50\n",
      "现在是星期三的18:50\n",
      "Python语言\n"
     ]
    }
   ],
   "source": [
    "day = input(\"星期几：\")\n",
    "hour = input(\"小时：\")\n",
    "minute = input(\"分钟：\")\n",
    "now = int(hour + minute)\n",
    "print(\"现在是星期{}的{}:{}\".format(day, hour, minute))\n",
    "\n",
    "if day == \"一\":\n",
    "    if 1035 < now < 1200:\n",
    "        print(\"羽毛球\")\n",
    "    elif 1430 < now < 1650:\n",
    "        print(\"用户与视觉界面设计\")\n",
    "    else:\n",
    "        print(\"无课。\")\n",
    "elif day == \"二\":\n",
    "    if 1250 < now < 1420:\n",
    "        print(\"Illustrator软件应用\")\n",
    "    else:\n",
    "        print(\"无课。\")\n",
    "elif day == \"三\":\n",
    "    if 800 < now < 1025:\n",
    "        print(\"毛泽东思想和中国特色社会主义理论体系概论\")\n",
    "    elif 1250 < now < 1420:\n",
    "        print(\"大学英语（三）\")\n",
    "    elif 1845 < now < 2055:\n",
    "        print(\"Python语言\")\n",
    "    else:\n",
    "        print(\"无课。\")\n",
    "elif day == \"四\":\n",
    "    if 1610 < now < 1735:\n",
    "        print(\"日语入门\")\n",
    "    else:\n",
    "        print(\"无课。\")\n",
    "elif day == \"五\":\n",
    "    if 800 < now < 930:\n",
    "        print(\"大学英语（三）\")\n",
    "    elif 945 < now < 1200:\n",
    "        print(\"API、机器学习与人工智能\")\n",
    "    elif 1250 < now < 1420:\n",
    "        print(\"毛概实践\")\n",
    "    else:\n",
    "        print(\"无课。\")\n",
    "else:\n",
    "    print(\"周末无课！\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "当前时间23:08\n",
      "无课。\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "\n",
    "today = time.strftime(\"%A\")\n",
    "now = int(time.strftime(\"%H%M\"))\n",
    "\n",
    "print(\"当前时间{}\".format(time.strftime(\"%H:%M\")))\n",
    "if today == \"Monday\":\n",
    "    if 1035 < now < 1200:\n",
    "        print(\"羽毛球\")\n",
    "    elif 1430 < now < 1650:\n",
    "        print(\"用户与视觉界面设计\")\n",
    "    else:\n",
    "        print(\"无课。\")\n",
    "elif today == \"Tuesday\":\n",
    "    if 1250 < now < 1420:\n",
    "        print(\"Illustrator软件应用\")\n",
    "    else:\n",
    "        print(\"无课。\")\n",
    "elif today == \"Wednesday\":\n",
    "    if 800 < now < 1025:\n",
    "        print(\"毛泽东思想和中国特色社会主义理论体系概论\")\n",
    "    elif 1250 < now < 1420:\n",
    "        print(\"大学英语（三）\")\n",
    "    elif 1845 < now < 2055:\n",
    "        print(\"Python语言\")\n",
    "    else:\n",
    "        print(\"无课。\")\n",
    "elif today == \"Thursday\":\n",
    "    if 1610 < now < 1735:\n",
    "        print(\"日语入门\")\n",
    "    else:\n",
    "        print(\"无课。\")\n",
    "elif today == \"Friday\":\n",
    "    if 800 < now < 930:\n",
    "        print(\"大学英语（三）\")\n",
    "    elif 945 < now < 1200:\n",
    "        print(\"API、机器学习与人工智能\")\n",
    "    elif 1250 < now < 1420:\n",
    "        print(\"毛概实践\")\n",
    "    else:\n",
    "        print(\"无课。\")\n",
    "else:\n",
    "    print(\"周末无课！\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### for 循环 内置函数range()\n",
    "*用例1 循环迭代数字变量*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "for i in [1,2,3]:\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*用例2循环迭代字符串变量*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "H\n",
      "i\n",
      "!\n"
     ]
    }
   ],
   "source": [
    "for ch in \"Hi!\":\n",
    "    print(ch)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*用例3 迭代指定的次数*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Head First Rocks!\n",
      "Head First Rocks!\n",
      "Head First Rocks!\n",
      "Head First Rocks!\n",
      "Head First Rocks!\n"
     ]
    }
   ],
   "source": [
    "for num in range(5):\n",
    "    print('Head First Rocks!')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**range 实验：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[99,\n",
       " 98,\n",
       " 97,\n",
       " 96,\n",
       " 95,\n",
       " 94,\n",
       " 93,\n",
       " 92,\n",
       " 91,\n",
       " 90,\n",
       " 89,\n",
       " 88,\n",
       " 87,\n",
       " 86,\n",
       " 85,\n",
       " 84,\n",
       " 83,\n",
       " 82,\n",
       " 81,\n",
       " 80,\n",
       " 79,\n",
       " 78,\n",
       " 77,\n",
       " 76,\n",
       " 75,\n",
       " 74,\n",
       " 73,\n",
       " 72,\n",
       " 71,\n",
       " 70,\n",
       " 69,\n",
       " 68,\n",
       " 67,\n",
       " 66,\n",
       " 65,\n",
       " 64,\n",
       " 63,\n",
       " 62,\n",
       " 61,\n",
       " 60,\n",
       " 59,\n",
       " 58,\n",
       " 57,\n",
       " 56,\n",
       " 55,\n",
       " 54,\n",
       " 53,\n",
       " 52,\n",
       " 51,\n",
       " 50,\n",
       " 49,\n",
       " 48,\n",
       " 47,\n",
       " 46,\n",
       " 45,\n",
       " 44,\n",
       " 43,\n",
       " 42,\n",
       " 41,\n",
       " 40,\n",
       " 39,\n",
       " 38,\n",
       " 37,\n",
       " 36,\n",
       " 35,\n",
       " 34,\n",
       " 33,\n",
       " 32,\n",
       " 31,\n",
       " 30,\n",
       " 29,\n",
       " 28,\n",
       " 27,\n",
       " 26,\n",
       " 25,\n",
       " 24,\n",
       " 23,\n",
       " 22,\n",
       " 21,\n",
       " 20,\n",
       " 19,\n",
       " 18,\n",
       " 17,\n",
       " 16,\n",
       " 15,\n",
       " 14,\n",
       " 13,\n",
       " 12,\n",
       " 11,\n",
       " 10,\n",
       " 9,\n",
       " 8,\n",
       " 7,\n",
       " 6,\n",
       " 5,\n",
       " 4,\n",
       " 3,\n",
       " 2,\n",
       " 1]"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "range(5)\n",
    "\n",
    "list(range(5))\n",
    "\n",
    "list(range(5,10))\n",
    "\n",
    "list(range(0,10,2))\n",
    "\n",
    "list(range(10,0,-2))\n",
    "\n",
    "list(range(10,0,2))\n",
    "\n",
    "list(range(99,0,-1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### random模块\n",
    "```python\n",
    "import random\n",
    "print(random.random())\n",
    "#random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0\n",
    "```\n",
    "```python\n",
    "print (random.randint(1,7)) \n",
    "#random.randint()的函数原型为：random.randint(a, b)，用于生成一个指定范围内的整数。\n",
    "# 其中参数a是下限，参数b是上限，生成的随机数n: a <= n <= b\n",
    "```\n",
    "**大脑 P35测试：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This second seems a little odd.\n",
      "Not an odd second.\n",
      "This second seems a little odd.\n",
      "This second seems a little odd.\n",
      "Not an odd second.\n"
     ]
    }
   ],
   "source": [
    "from datetime import datetime\n",
    "\n",
    "import random\n",
    "import time\n",
    "\n",
    "odds = [1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59]\n",
    "\n",
    "for i in range(5):\n",
    "    right_this_second = datetime.today().second\n",
    "    if right_this_second in odds:\n",
    "        print(\"This second seems a little odd.\")\n",
    "    else:\n",
    "        print(\"Not an odd second.\")\n",
    "    wait_time = random.randint(1,5)\n",
    "    time.sleep(wait_time)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 小小总结\n",
    "- cmd/IDLE 中的交互执行：偶尔执行一些简单的语句、测试\n",
    "- jupyter notebook：介于交互和脚本之间的（可做笔记，关心中间过程的输出）\n",
    "- IDLE 小型项目，学习初期的选择，功能完善\n",
    "- PyCharm 中大型项目中方便组织较多文件，功能更为丰富\n",
    "- pycharm 将成为学习python之路上的最重要的工具。\n",
    "- upyter 将成为我们数据科学（包含大数据、数据分析）之路的重要工具"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 变量（数字、字符串、对象）\n",
    "**1、数字（Numbers）**\n",
    "```python\n",
    ">>> 2 + 2\n",
    "4\n",
    ">>> 50 - 5*6\n",
    "20\n",
    ">>> (50 - 5*6) / 4\n",
    "5.0\n",
    ">>> 8 / 5  # division always returns a floating point number\n",
    "1.6\n",
    "```\n",
    "```python\n",
    ">>> 17 / 3  # classic division returns a float\n",
    "5.666666666666667\n",
    ">>>\n",
    ">>> 17 // 3  # floor division discards the fractional part\n",
    "5\n",
    ">>> 17 % 3  # the % operator returns the remainder of the division\n",
    "2\n",
    ">>> 5 * 3 + 2  # result * divisor + remainder\n",
    "17\n",
    "```\n",
    "```python\n",
    "import random\n",
    "wait_time = random.randint(1,60)\n",
    "print(wait_time)\n",
    "```\n",
    "**2、字符串（Strings）**\n",
    "```python\n",
    ">>> 'spam eggs'  # single quotes\n",
    "'spam eggs'\n",
    ">>> 'doesn\\'t'  # use \\' to escape the single quote...\n",
    "\"doesn't\"\n",
    ">>> \"doesn't\"  # ...or use double quotes instead\n",
    "\"doesn't\"\n",
    ">>> '\"Yes,\" they said.'\n",
    "'\"Yes,\" they said.'\n",
    ">>> \"\\\"Yes,\\\" they said.\"\n",
    "'\"Yes,\" they said.'\n",
    ">>> '\"Isn\\'t,\" they said.'\n",
    "'\"Isn\\'t,\" they said.'\n",
    "```\n",
    "**3、对象**\n",
    "\n",
    "*python中“一切皆是对象”*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 注释\n",
    "- 单行注释：# 被注释内容"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# -*- coding:utf-8 -*-\n",
    "# Author:Xiaoyan"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 多行注释：\"\"\" 被注释内容 \"\"\"  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'\\nimport random\\nwait_time = random.randint(1,60)\\nprint(wait_time)\\n\\nword = \"bottles\"\\nprint(word)\\n'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'''\n",
    "import random\n",
    "wait_time = random.randint(1,60)\n",
    "print(wait_time)\n",
    "\n",
    "word = \"bottles\"\n",
    "print(word)\n",
    "'''"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 除此之外，\"\"\" 被注释内容 \"\"\"  还可以打印变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "import random\n",
      "wait_time = random.randint(1,60)\n",
      "print(wait_time)\n",
      "\n",
      "word = \"bottles\"\n",
      "print(word)\n",
      "\n"
     ]
    }
   ],
   "source": [
    "test1 ='''\n",
    "import random\n",
    "wait_time = random.randint(1,60)\n",
    "print(wait_time)\n",
    "\n",
    "word = \"bottles\"\n",
    "print(word)\n",
    "'''\n",
    "print(test1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 用户输入"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "username:Xiaoyan\n",
      "password:10086\n",
      "Xiaoyan 10086\n"
     ]
    }
   ],
   "source": [
    "# -*- coding:utf-8 -*-\n",
    "# Author:Xiaoyan\n",
    "\n",
    "username = input(\"username:\")\n",
    "password = input(\"password:\")\n",
    "\n",
    "print(username,password)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "** 字符串拼接+打印：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "name:Xiaoyan\n",
      "age:18\n",
      "job:student\n",
      "salary:0\n",
      "----- INFO OF Xiaoyan------\n",
      "age:18\n",
      "job:student\n",
      "salary:0\n"
     ]
    }
   ],
   "source": [
    "name = input(\"name:\")\n",
    "age = input(\"age:\")\n",
    "job = input(\"job:\")\n",
    "salary = input(\"salary:\")\n",
    "\n",
    "info = '''----- INFO OF ''' + name +'''------''' + '''\n",
    "age:''' + age+'''\n",
    "job:''' + job +'''\n",
    "salary:'''+salary\n",
    "\n",
    "print(info)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**利用%s 占位符**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "name:Xiaoyan\n",
      "age:18\n",
      "job:student\n",
      "salary:0\n",
      "-------INFO OF Xiaoyan -------\n",
      "Name:Xiaoyan\n",
      "Age:18\n",
      "Job:student\n",
      "Salary:0\n",
      "\n"
     ]
    }
   ],
   "source": [
    "name = input(\"name:\")\n",
    "age = input(\"age:\")\n",
    "job = input(\"job:\")\n",
    "salary = input(\"salary:\")\n",
    "\n",
    "info = '''-------INFO OF %s -------\n",
    "Name:%s\n",
    "Age:%s\n",
    "Job:%s\n",
    "Salary:%s\n",
    "'''% (name,name,age,job,salary)\n",
    "\n",
    "print(info)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- %s代表 string\n",
    "- %d代表 number\n",
    "- %f代表 float\n",
    "- 更进一步：设置数据类型，将age、salary设置为number"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "name:Xiaoyan\n",
      "age:18\n",
      "job:student\n",
      "salary:0\n",
      "-------INFO OF Xiaoyan -------\n",
      "Name:Xiaoyan\n",
      "Age:18\n",
      "Job:student\n",
      "Salary:0\n",
      "\n"
     ]
    }
   ],
   "source": [
    "name = input(\"name:\")\n",
    "age = int(input(\"age:\"))  #注意！ python中默认所有的输入均为string\n",
    "job = input(\"job:\")\n",
    "salary = int(input(\"salary:\"))\n",
    "\n",
    "info = '''-------INFO OF %s -------\n",
    "Name:%s\n",
    "Age:%d\n",
    "Job:%s\n",
    "Salary:%d\n",
    "'''% (name,name,age,job,salary)\n",
    "\n",
    "print(info)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**.format()：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-------INFO OF Xiaoyan -------\n",
      "Name:Xiaoyan\n",
      "Age:18\n",
      "Job:student\n",
      "Salary:0\n",
      "\n"
     ]
    }
   ],
   "source": [
    "info2 =  '''-------INFO OF {_name} -------\n",
    "Name:{_name}\n",
    "Age:{_age}\n",
    "Job:{_job}\n",
    "Salary:{_salary}\n",
    "'''.format(_name=name,\n",
    "           _age=age,\n",
    "           _job=job,\n",
    "           _salary=salary)\n",
    "print(info2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-------INFO OF Xiaoyan -------\n",
      "Name:Xiaoyan\n",
      "Age:18\n",
      "Job:student\n",
      "Salary:0\n",
      "\n"
     ]
    }
   ],
   "source": [
    "info3 =  '''-------INFO OF {0} -------\n",
    "Name:{0}\n",
    "Age:{1}\n",
    "Job:{2}\n",
    "Salary:{3}\n",
    "'''.format(name,age,job,salary)\n",
    "print(info3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "weekday:Sunday\n",
      "mood:happy\n",
      "Rest.\n"
     ]
    }
   ],
   "source": [
    "today = input(\"weekday:\")\n",
    "if today == \"Saturday\":\n",
    "    print(\"Party!\")\n",
    "elif today == \"Sunday\":\n",
    "    condition = input(\"mood:\")\n",
    "    if condition == \"Headache\":\n",
    "        print(\"Recover, then rest.\")\n",
    "    else:\n",
    "        print(\"Rest.\")\n",
    "else:\n",
    "    print(\"Work, work, work.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " ### Python内置数据结构\n",
    " #### 列表\n",
    " - python中list列表是一种数据类型，列表会将所有元素都放在一对中括号[]中，相邻元素之间用逗号分隔,它是有序和可变的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['你', '我', '他', '她']\n"
     ]
    }
   ],
   "source": [
    "names = ['你', '我', '他', '她']\n",
    "print(names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['你', '我', '他', '她', '它']\n"
     ]
    }
   ],
   "source": [
    "# 1、增加 \n",
    "#append 增加在列表末尾\n",
    "names.append(\"它\")\n",
    "print(names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['你', '我', '牠', '他', '她', '它']\n"
     ]
    }
   ],
   "source": [
    "# insert增加在指定位置\n",
    "names.insert(2, '牠')\n",
    "print(names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['你', '我', '牠', '他', '她']\n"
     ]
    }
   ],
   "source": [
    "# 2、删除 \n",
    "\n",
    "# # 2、删除 pop() 1\\什么都不填，删除末尾 2\\删除指定位置的列表内容\n",
    "names.pop()\n",
    "print(names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "牠\n",
      "['你', '我', '他', '她']\n"
     ]
    }
   ],
   "source": [
    "pop_names = names.pop(2)\n",
    "print(pop_names)\n",
    "print(names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['你', '我', '她']\n"
     ]
    }
   ],
   "source": [
    "# remove 可以删除指定内容\n",
    "names.remove('他')\n",
    "print(names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['您', '我', '她']\n"
     ]
    }
   ],
   "source": [
    "# 3、修改  需要清楚知道位置\n",
    "\n",
    "names[0] = '您'\n",
    "print(names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['你', '我', '她']\n"
     ]
    }
   ],
   "source": [
    "# 4、查 ------>改或者其他操作\n",
    "\n",
    "name = '您'\n",
    "if name in names:\n",
    "    names[names.index(name)] = '你'\n",
    "    print(names)\n",
    "else:\n",
    "    print(\"%s 不在我们的列表中\" % (name))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 列表的切片"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我 他\n"
     ]
    }
   ],
   "source": [
    "names = ['你', '我', '他', '她']\n",
    "print(names[1],names[2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['我', '他']\n"
     ]
    }
   ],
   "source": [
    "# 切片 仍然是一个列表 \n",
    "print(names[1:3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['你', '我', '他']\n",
      "['你', '我', '他']\n"
     ]
    }
   ],
   "source": [
    "# 从列表首位开始，可以省略0\n",
    "print(names[0:3])\n",
    "print(names[:3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['我', '他']\n",
      "['我', '他', '她']\n"
     ]
    }
   ],
   "source": [
    "# 从列表末位开始取\n",
    "print(names[-3:-1])\n",
    "print(names[-3:])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[]\n"
     ]
    }
   ],
   "source": [
    "#clear 删除所有元素\n",
    "names.clear()\n",
    "print(names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 1, 1, 2, 2, 2, 3, 3, 4]\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "# sort 对列表进行排序\n",
    "# count统计字符串里某个字符出现的次数\n",
    "nums = [1, 2, 3, 3, 1, 2, 4, 1, 2]\n",
    "nums.sort()\n",
    "print(nums)\n",
    "print(nums.count(2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 元组(tuple)\n",
    "- 元组是一个一旦创建就不能改变的列表。任何情况下这个元组都不能再改变。通常可以把元组想象成一个常量列表。\n",
    "\n",
    "**语法：**\n",
    "元组只有两个方法，count和index。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'tuple'>\n",
      "1\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "a = (3,2,1,4,5,2,2,4,5,6,4)\n",
    "print(type(a))\n",
    "print(a.index(2))\n",
    "print(a.count(2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "12345"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t = 12345, 54321, 'hello!'\n",
    "t[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(12345, 54321, 'hello!')"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Tuples may be nested:\n",
    "u = t, (1, 2, 3, 4, 5)\n",
    "u"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "([1, 2, 3], [3, 2, 1])"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "v = ([1, 2, 3], [3, 2, 1])\n",
    "v"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### while 循环\n",
    "- 有一种循环叫做死循环，一经触发，就运行到天荒地老。\n",
    "\n",
    "**天荒地老代码：**\n",
    "```python\n",
    "count = 0\n",
    "while True:\n",
    "   print(\"你是风儿我是沙,缠缠绵绵到天涯...\",count)\n",
    "   count +=1\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**如何停止循环？**\n",
    "- 引入break："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你是风儿我是沙,缠缠绵绵到天涯... 0\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 1\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 2\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 3\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 4\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 5\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 6\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 7\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 8\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 9\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 10\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 11\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 12\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 13\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 14\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 15\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 16\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 17\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 18\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 19\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 20\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 21\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 22\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 23\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 24\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 25\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 26\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 27\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 28\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 29\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 30\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 31\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 32\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 33\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 34\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 35\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 36\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 37\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 38\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 39\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 40\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 41\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 42\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 43\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 44\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 45\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 46\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 47\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 48\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 49\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 50\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 51\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 52\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 53\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 54\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 55\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 56\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 57\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 58\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 59\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 60\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 61\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 62\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 63\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 64\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 65\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 66\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 67\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 68\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 69\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 70\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 71\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 72\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 73\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 74\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 75\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 76\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 77\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 78\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 79\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 80\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 81\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 82\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 83\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 84\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 85\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 86\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 87\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 88\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 89\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 90\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 91\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 92\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 93\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 94\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 95\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 96\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 97\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 98\n",
      "你是风儿我是沙,缠缠绵绵到天涯... 99\n"
     ]
    }
   ],
   "source": [
    "count = 0\n",
    "while True:\n",
    "    print(\"你是风儿我是沙,缠缠绵绵到天涯...\",count)\n",
    "    count +=1\n",
    "    if count == 100:  #加入结束条件\n",
    "        break               #跳出循环"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**猜数字游戏：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "这是一个位于 1-20 之间的数\n",
      "请输入猜测的数：\n",
      "15\n",
      "太小啦，请往大的猜！\n",
      "请输入猜测的数：\n",
      "18\n",
      "太大啦，请往小的猜！\n",
      "请输入猜测的数：\n",
      "17\n",
      "恭喜你,答对啦~真棒！就是 17\n"
     ]
    }
   ],
   "source": [
    "import random   #引入生成随机数的模块\n",
    "secretNum = random.randint(1,20)\n",
    "print(\"这是一个位于 1-20 之间的数\")\n",
    "#设定用户只能猜 3 次\n",
    "for number in range(1,4):\n",
    "    print(\"请输入猜测的数：\")\n",
    "    guess = int(input())\n",
    "    if guess == 0:\n",
    "        break\n",
    "    if guess < secretNum:\n",
    "        print(\"太小啦，请往大的猜！\")\n",
    "    elif guess > secretNum:\n",
    "        print(\"太大啦，请往小的猜！\")\n",
    "    else:\n",
    "        break\n",
    "if(guess == secretNum):\n",
    "    print(\"恭喜你,答对啦~真棒！就是\",str(guess))\n",
    "else:\n",
    "    print(\"啊哈哈哈哈~ 还猜不出来，你好笨啊，正确的答案应该是\",str(secretNum))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典操作（dict）\n",
    "- 字典是另一种可变容器模型，且可存储任意类型对象。\n",
    "- 字典的每个键值 key=>value 对用冒号 : 分割，每个键值对之间用逗号 , 分割，整个字典包括在花括号 {} 中。\n",
    "\n",
    "**语法**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'stu1901': 'Xiaoyan', 'stu1902': 'Guijun', 'stu1903': 'Xiaobing'}\n"
     ]
    }
   ],
   "source": [
    "info = {\n",
    "    \"stu1901\":\"Xiaoyan\",\n",
    "    \"stu1902\":\"Guijun\",\n",
    "    \"stu1903\":\"Xiaobing\"\n",
    "}\n",
    "print(info)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**创建字典的常用方法**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'stu1901': 'Xiaoyan', 'stu1902': 'Guijun', 'stu1903': 'Xiaobing'}\n",
      "{'stu1901': 'Xiaoyan', 'stu1902': 'Guijun', 'stu1903': 'Xiaobing'}\n",
      "{'stu1901': 'Xiaoyan', 'stu1902': 'Guijun', 'stu1903': 'Xiaobing'}\n"
     ]
    }
   ],
   "source": [
    "info1 = {\n",
    "    \"stu1901\":\"Xiaoyan\",\n",
    "    \"stu1902\":\"Guijun\",\n",
    "    \"stu1903\":\"Xiaobing\"\n",
    "}\n",
    "\n",
    "print(info1)\n",
    "\n",
    "info2 = dict(stu1901=\"Xiaoyan\",stu1902=\"Guijun\",stu1903=\"Xiaobing\")\n",
    "print(info2)\n",
    "\n",
    "info3 = {}\n",
    "info3[\"stu1901\"]=\"Xiaoyan\"\n",
    "info3[\"stu1902\"]=\"Guijun\"\n",
    "info3[\"stu1903\"]=\"Xiaobing\"\n",
    "print(info3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**增加**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'stu1901': 'Xiaoyan', 'stu1902': 'Guijun', 'stu1903': 'Xiaobing', 'stu1904': 'Damao'}\n"
     ]
    }
   ],
   "source": [
    "info[\"stu1904\"] = \"Damao\"\n",
    "print(info)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**修改**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'stu1901': 'Xiaoyan', 'stu1902': 'Guijun', 'stu1903': 'Xiaobing', 'stu1904': 'Miaomiao'}\n"
     ]
    }
   ],
   "source": [
    "info[\"stu1904\"] = \"Miaomiao\"\n",
    "print(info)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**删除**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'stu1901': 'Xiaoyan', 'stu1902': 'Guijun', 'stu1903': 'Xiaobing'}\n"
     ]
    }
   ],
   "source": [
    "info.pop(\"stu1904\") #标准删除姿势\n",
    "print(info)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'stu1902': 'Guijun', 'stu1903': 'Xiaobing'}\n"
     ]
    }
   ],
   "source": [
    "del info[\"stu1901\"] #换个姿势删除\n",
    "print(info)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'stu1901': 'Xiaoyan', 'stu1902': 'Guijun', 'stu1903': 'Xiaobing'}\n",
      "{'stu1901': 'Xiaoyan', 'stu1902': 'Guijun'}\n"
     ]
    }
   ],
   "source": [
    "#随机删除\n",
    "info = {\"stu1901\":\"Xiaoyan\",\"stu1902\":\"Guijun\",\"stu1903\":\"Xiaobing\"}\n",
    "print(info)\n",
    "info.popitem()\n",
    "print(info)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**查找**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "info = {\"stu1901\":\"Xiaoyan\",\"stu1902\":\"Guijun\",\"stu1903\":\"Xiaobing\"}\n",
    "info\n",
    "print(\"stu1901\" in info) #标准用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Guijun\n"
     ]
    }
   ],
   "source": [
    "print(info.get(\"stu1902\")) #获取"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Guijun\n"
     ]
    }
   ],
   "source": [
    "print(info[\"stu1902\"]) #同上，但看下面"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    }
   ],
   "source": [
    "KeyError: 'stu1905'\n",
    "print(info.get(\"stu1905\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**可以在字典上使用的内建方法**\n",
    "\n",
    "| 序号  | 名称  |描述   |\n",
    "|---|---|---|\n",
    "|1  |  dict.clear() | 删除字典中的所有元素  |\n",
    "| 2 |  dict.copy()  |返回字典的副本   |\n",
    "| 3  | dict.pop()  |  删除拥有指定键的元素 |\n",
    "|  4 |dict.remove()   | 移除指定的元素  \n",
    "|  5 |  dict.update() | 使用指定的键值对字典进行更新 |\n",
    "| 6 |  dict.keys() | 返回包含字典键的列表 |\n",
    "|  7 |  dict.fromkeys() | 返回拥有指定键和值的字典 |\n",
    "|  8 |  dict.items() | 返回包含每个键值对的元组的列表 |\n",
    "|  9 |  dict.popitem() | 删除最后插入的键值对 |\n",
    "|  10|  dict.values() | 返回字典中所有值的列表 |"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 字典的嵌套/访问一个复杂数据结构的数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'Arthur': {'Gender': 'Male',\n",
      "            'Home Planet': 'Earth',\n",
      "            'Name': 'Arthur Dent',\n",
      "            'Occupation': 'Sandwich-Maker'},\n",
      " 'Ford': {'Gender': 'Male',\n",
      "          'Home Planet': 'Betelgeuse Seven',\n",
      "          'Name': 'Ford Prefect',\n",
      "          'Occupation': 'Researcher'},\n",
      " 'Marvin': {'Gender': 'Unknown',\n",
      "            'Home Planet': 'Unknown',\n",
      "            'Name': 'Marvin',\n",
      "            'Occupation': 'Paranoid Android'},\n",
      " 'Tricia': {'Gender': 'Female',\n",
      "            'Home Planet': 'Earth',\n",
      "            'Name': 'Tricia McMillan',\n",
      "            'Occupation': 'Mathematician'}}\n"
     ]
    }
   ],
   "source": [
    "import pprint\n",
    "people = {}\n",
    "people['Ford'] = {\"Name\":'Ford Prefect',\n",
    "                  \"Gender\":'Male',\n",
    "                  \"Occupation\":'Researcher',\n",
    "                  \"Home Planet\":'Betelgeuse Seven'}\n",
    "people['Arthur'] = {\"Name\":'Arthur Dent',\n",
    "                  \"Gender\":'Male',\n",
    "                  \"Occupation\":'Sandwich-Maker',\n",
    "                  \"Home Planet\":'Earth'}\n",
    "people['Tricia'] = {\"Name\":'Tricia McMillan',\n",
    "                    \"Gender\":'Female',\n",
    "                    \"Occupation\":'Mathematician',\n",
    "                    \"Home Planet\":'Earth'}\n",
    "people['Marvin'] = {\"Name\":'Marvin',\n",
    "                    \"Gender\":'Unknown',\n",
    "                    \"Occupation\":'Paranoid Android',\n",
    "                    \"Home Planet\":'Unknown'}\n",
    "pprint.pprint(people)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 集合操作（sets）\n",
    "- 集合（set）是一个无序的不重复元素序列。\n",
    "- 可以使用大括号 { } 或者 set() 函数创建集合\n",
    "\n",
    "*注意：创建一个空集合必须用 set() 而不是 { }，因为 { } 是用来创建一个空字典。*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "list_2: {1, 2, 3, 4, 5, 6, 7} \n",
      " <class 'set'>\n",
      "list_3: {0, 1, 66, 3, 4, 7, 8}\n"
     ]
    }
   ],
   "source": [
    "list_1 = [1,2,5,6,7,2,3,2,4,4]\n",
    "\n",
    "list_2 = set(list_1)\n",
    "list_3 = set([1,3,4,0,8,66,7])\n",
    "\n",
    "print(\"list_2:\",list_2,\"\\n\",type(list_2))\n",
    "print(\"list_3:\",list_3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 3, 4, 7}\n",
      "{1, 3, 4, 7}\n"
     ]
    }
   ],
   "source": [
    "# 交集\n",
    "print(list_2.intersection(list_3))\n",
    "print(list_2 & list_3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0, 1, 2, 3, 4, 5, 6, 7, 66, 8}\n",
      "{0, 1, 2, 3, 4, 5, 6, 7, 66, 8}\n"
     ]
    }
   ],
   "source": [
    "# 并集\n",
    "print(list_2.union(list_3))\n",
    "print(list_2 | list_3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{2, 5, 6}\n",
      "{2, 5, 6}\n",
      "{0, 8, 66}\n",
      "{0, 8, 66}\n"
     ]
    }
   ],
   "source": [
    "# 差集\n",
    "print(list_2.difference(list_3))\n",
    "print(list_2 - list_3)\n",
    "\n",
    "print(list_3.difference(list_2))\n",
    "print(list_3 - list_2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "# 子集\n",
    "print(list_2.issubset(list_3))  #子集\n",
    "print(list_2.issuperset(list_3))  #父集\n",
    "list_4 = set([2,3])\n",
    "print(list_4.issubset(list_2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{0, 66, 2, 5, 6, 8}\n"
     ]
    }
   ],
   "source": [
    "# 对称差集\n",
    "print(list_2.symmetric_difference(list_3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 66, 3, 4, 7, 8}\n"
     ]
    }
   ],
   "source": [
    "list_3 = set([1,3,4,0,8,66,7])\n",
    "list_3.pop()  # pop() 方法用于随机移除一个元素。\n",
    "print(list_3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "set()\n"
     ]
    }
   ],
   "source": [
    "list_3.clear() #清空\n",
    "print(list_3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{5}\n"
     ]
    }
   ],
   "source": [
    "list_3.add(5)\n",
    "print(list_3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{5}\n"
     ]
    }
   ],
   "source": [
    "\n",
    "#该方法不同于 remove() 方法，因为 remove() 方法在移除一个不存在的元素时会发生错误，而 discard() 方法不会。\n",
    "list_3.discard(9)\n",
    "print(list_3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{5}\n"
     ]
    }
   ],
   "source": [
    "list_4 = list_3.copy()\n",
    "print(list_4)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "#### 集合内置方法\n",
    "\n",
    "| 序号  | 名称  |描述   |\n",
    "|---|---|---|\n",
    "|  1 | set.add()  |  为集合添加元素 |\n",
    "| 2  |  set.clear() | 移除集合中的所有元素  |\n",
    "|  3 |  set.copy()  |拷贝一个集合   |\n",
    "| 4  | set.difference()\t  |  返回多个集合的差集 |\n",
    "|  5 |  set.difference_update() |  移除集合中的元素，该元素在指定的集合也存在。 |\n",
    "| 6  |  set.discard() | 删除集合中指定的元素  |\n",
    "|  7 |  set.intersecrion()|\t返回集合的交集   |\n",
    "| 8  |  ste.isdisjoint()\t | 判断两个集合是否包含相同的元素，如果没有返回 True，否则返回 False。  |\n",
    "|  9 |  set.issubset() |  判断指定集合是否为该方法参数集合的子集。 |\n",
    "| 10  | set.pop()  |  随机移除元素 |\n",
    "|  11 |set.remove()   | 移除指定的元素  |\n",
    "|  12 |  set.symmetric_difference() |  返回两个集合中不重复的元素集合。 |\n",
    "| 13  |  set.symmetric_difference_update() |  移除当前集合中在另外一个指定集合相同的元素，并将另外一个指定集合中不同的元素插入到当前集合中。 |\n",
    "|   14| set.union()\t  |  返回两个集合的并集 |\n",
    "|  15 |  set.update() | 给集合添加元素 |"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 函数\n",
    "#### 函数的定义\n",
    "- 函数的一般定义（中学/数学）：函数的近代定义是给定一个数集A，假设其中的元素为x，对A中的元素x施加对应法则f，记作f（x），得到另一数集B，假设B中的元素为y，则y与x之间的等量关系可以用y=f（x）表示，函数概念含有三个要素：定义域A、值域C和对应法则f。\n",
    "- 编程语言中函数的定义（计算机）：函数是逻辑结构化和过程化的一种编程方法。\n",
    "\n",
    "**函数的定义方法(案例)：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\"\\ndef:定义函数的关键字\\nflb：函数名\\n(n)：定义函数的参数\\n：文档描述\\n代码块：\\n     a, b = 0, 1\\n     while a < n:\\n        print(a, end=' ')\\n         a, b = b, a+b\\n     print()\\n\""
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def fib(n):    # write Fibonacci series up to n\n",
    "    \"\"\"Print a Fibonacci series up to n.\"\"\"\n",
    "    a, b = 0, 1\n",
    "    while a < n:\n",
    "        print(a, end=' ')\n",
    "        a, b = b, a+b\n",
    "        print()\n",
    "\n",
    "\"\"\"\n",
    "def:定义函数的关键字\n",
    "flb：函数名\n",
    "(n)：定义函数的参数\n",
    "\"\"\"\"\"\"：文档描述\n",
    "代码块：\n",
    "     a, b = 0, 1\n",
    "     while a < n:\n",
    "        print(a, end=' ')\n",
    "         a, b = b, a+b\n",
    "     print()\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide a word to search for vowels:containing\n",
      "o\n",
      "a\n",
      "i\n",
      "Provide a word to search for vowels:intersection\n",
      "o\n",
      "e\n",
      "i\n"
     ]
    }
   ],
   "source": [
    "def search4vowels():\n",
    "    vowels = set('aeiou')\n",
    "    word = input(\"Provide a word to search for vowels:\")\n",
    "    found = vowels.intersection(set(word))\n",
    "    for vowel in found:\n",
    "        print(vowel)\n",
    "\n",
    "search4vowels()\n",
    "search4vowels() #可以重复多次调用\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 如何使用函数（传递实参）\n",
    "**函数的使用方法**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def fib2(n):  # return Fibonacci series up to n\n",
    "    \"\"\"Return a list containing the Fibonacci series up to n.\"\"\"\n",
    "    result = []\n",
    "    a, b = 0, 1\n",
    "    while a < n:\n",
    "        result.append(a)    # see below\n",
    "        a, b = b, a+b\n",
    "    return result\n",
    "\n",
    "f100 = fib2(100)    # call it\n",
    "f100                # write the result\n",
    "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 向函数传递信息\n",
    "*针对greet_user()只要稍作修改，就可不仅实现Hello，还可以将用户名字作为抬头：*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello,Xiaoyan!\n"
     ]
    }
   ],
   "source": [
    "def greet_user(username):    \n",
    "    \"\"\"显示简单的问候语\"\"\"    \n",
    "    print(\"hello,\"+username.title()+\"!\")         \n",
    "\n",
    "greet_user(\"Xiaoyan\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 实参和形参\n",
    "- greet_user(username) #username 为形参；函数完成其工作时所需要的信息。\n",
    "- greet_user(\"zhichao\") #\"zhichao\"为实参；实参是调用函数时传递给函数的信息。\n",
    "\n",
    "- 形参：形式参数，不是实际存在的，是虚拟变量。在定义函数和函数体的时候使用形参，目的是在函数调用时接收实参\n",
    "- 实参：实际参数，调用函数时传递给函数的参数，可以是常量、变量，表达式，函数，传给形参\n",
    "\n",
    "- 区别：形参是虚拟的，不占用空间，形参变量只有在被调用时才分配内存单元，实参是一个变量，占用内存空间，数据传递单向，实参传给形参，不能倒过来。\n",
    "\n",
    "**传递实参：**\n",
    "\n",
    "*1、位置实参（基于实参的顺序）：*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "I have ahamster.\n",
      "Myhamster's name is Harry.\n",
      "\n",
      "I have acat.\n",
      "Mycat's name is Python.\n"
     ]
    }
   ],
   "source": [
    "def describe_pet(animal_type,pet_name):\n",
    "    \"\"\"显示宠物信息\"\"\"\n",
    "    print(\"\\nI have a\" + animal_type + \".\")\n",
    "    print(\"My\" + animal_type + \"'s name is \"+pet_name.title() + \".\")\n",
    "\n",
    "describe_pet('hamster','harry')\n",
    "describe_pet('cat','python')  #函数调用多次是一种效率极高的工作方式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*2 关键字参数*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "I have a hamster.\n",
      "Myhamster's name is Harry.\n",
      "\n",
      "I have a cat.\n",
      "Mycat's name is Python.\n"
     ]
    }
   ],
   "source": [
    "def describe_pet(pet_name,animal_type=\"dog\",):\n",
    "    \"\"\"显示宠物信息\"\"\"\n",
    "    print(\"\\nI have a \" + animal_type + \".\")\n",
    "    print(\"My\" + animal_type + \"'s name is \"+pet_name.title() + \".\")\n",
    "\n",
    "describe_pet(pet_name='harry',animal_type='hamster')  #关键字实参\n",
    "describe_pet(pet_name='python',animal_type='cat')  #关键字实参"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> **关键参数是不可以写在位置参数前面的**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 默认值\n",
    "- 编写函数时，可以给形参指定默认值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "I have a hamster.\n",
      "Myhamster's name is Harry.\n",
      "\n",
      "I have a cat.\n",
      "Mycat's name is Python.\n"
     ]
    }
   ],
   "source": [
    "def describe_pet(pet_name,animal_type=\"dog\",):\n",
    "    \"\"\"显示宠物信息\"\"\"\n",
    "    print(\"\\nI have a \" + animal_type + \".\")\n",
    "    print(\"My\" + animal_type + \"'s name is \"+pet_name.title() + \".\")\n",
    "\n",
    "describe_pet('harry','hamster')\n",
    "describe_pet('python','cat')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 像函数中传递列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, Hannah!\n",
      "Hello, Ty!\n",
      "Hello, Margot!\n"
     ]
    }
   ],
   "source": [
    "def greet_users(names):\n",
    "    \"\"\"向列表中的每位用户都发出简单的问候\"\"\"\n",
    "    for name in names:\n",
    "        msg = \"Hello, \"+name.title() +\"!\"\n",
    "        print(msg)\n",
    "\n",
    "usernames = ['hannah','ty','margot']\n",
    "greet_users(usernames)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 函数的返回值\n",
    "- 函数返回的值被称为函数的返回值；\n",
    "- 在函数中，可用return语句将值返回到调用函数的代码行；\n",
    "- 返回值能将你程序的大部分繁重工作移到函数中去完成，从而简化主程序。\n",
    "##### 返回简单值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Jimi Hendrix\n"
     ]
    }
   ],
   "source": [
    "def get_formatted_name(first_name,last_name):\n",
    "    \"\"\"返回整洁的姓名\"\"\"\n",
    "    full_name = first_name + ' '+ last_name\n",
    "    return full_name.title()\n",
    "\n",
    "musician = get_formatted_name('jimi','hendrix') #调用返回值的函数时，需要提供一个变量，用于存储返回的值\n",
    "print(musician)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 让实参变成可选的\n",
    "- 有时候，需要让实参变成可选的，这样使用函数的人就只需要在必要时候才提供额外信息。\n",
    "- 我们对：formatted_name1 进行扩展（函数的可扩展性）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Jimi Lee Hendrix\n"
     ]
    }
   ],
   "source": [
    "def get_formatted_name(first_name,middle_name,last_name):\n",
    "    \"\"\"返回整洁的姓名\"\"\"\n",
    "    full_name = first_name + ' '+middle_name+' '+ last_name\n",
    "    return full_name.title()\n",
    "\n",
    "musician = get_formatted_name('jimi','lee','hendrix') #有些人有中间名\n",
    "print(musician)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Jimi Hendrix Lee\n",
      "Jimi Hendrix\n"
     ]
    }
   ],
   "source": [
    "# 有些人不一定有中间名，那么对函数进行优化：\n",
    "\n",
    "def get_formatted_name(first_name,last_name,middle_name=''):  #复习关键字实参放后面\n",
    "    \"\"\"返回整洁的姓名\"\"\"\n",
    "    if middle_name:\n",
    "        full_name = first_name + ' '+middle_name+' '+ last_name\n",
    "    else:\n",
    "        full_name = first_name + ' ' + last_name\n",
    "    return full_name.title()\n",
    "\n",
    "musician = get_formatted_name('jimi','lee','hendrix')\n",
    "musician1 = get_formatted_name('jimi','hendrix')\n",
    "print(musician)\n",
    "print(musician1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 返回多个值\n",
    "- 函数可以返回任意类型的值，包括列表、字典和集合等较为复杂的数据结构。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'o', 'a', 'e', 'i'}\n"
     ]
    }
   ],
   "source": [
    "# 返回一个集合：\n",
    "def search4vowels(word):\n",
    "    \"\"\"Return a boolean based on any vowels found\"\"\"\n",
    "    vowels = set('aeiou')\n",
    "    found = vowels.intersection(set(word))\n",
    "    return found\n",
    "word = search4vowels('hello Zhichao')\n",
    "print(word)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'o', 'a', 'e', 'i'}\n"
     ]
    }
   ],
   "source": [
    "# 返回数据：\n",
    "def search4vowels(word):\n",
    "    \"\"\"Return a boolean based on any vowels found\"\"\"\n",
    "    vowels = set('aeiou')\n",
    "    return vowels.intersection(set(word))\n",
    "word = search4vowels('hello Zhichao')\n",
    "print(word)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'first': 'jimi', 'last': 'hendrix'}\n"
     ]
    }
   ],
   "source": [
    "# 返回字典：\n",
    "def build_person(first_name,last_name):\n",
    "    \"\"\"返回一个字典，其中包含有关一个人的信息\"\"\"\n",
    "    person = {'first':first_name,'last':last_name}\n",
    "    return person\n",
    " \n",
    "musician = build_person('jimi','hendrix')\n",
    "print(musician)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 使用注释改进文档\n",
    "- python3 注解的记法\n",
    "\n",
    "1.函数注解是可选的。\n",
    "\n",
    "2.函数注解可以提供信息。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function search4vowels in module __main__:\n",
      "\n",
      "search4vowels(word: str) -> set\n",
      "    Return a boolean based on any vowels found\n",
      "\n"
     ]
    }
   ],
   "source": [
    "def search4vowels(word:str) ->set:\n",
    "    \"\"\"Return a boolean based on any vowels found\"\"\"\n",
    "    vowels = set('aeiou')\n",
    "    return vowels.intersection(set(word))\n",
    "\n",
    "help(search4vowels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 传递任意数量的实参\n",
    "- 1.*args，传入多个参数，转化成元组。\n",
    "\n",
    " - 假如一个函数定义一个披萨的配料，但并不知道有多少配料需要加入，在参数不确定的情况下，我们引入任意数量的实参。\n",
    "- 2.**kwargs，把关键字参数，转化成字典。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Making a pizza with the following toppings\n",
      "--peperoni\n",
      "\n",
      "Making a pizza with the following toppings\n",
      "--mushroom\n",
      "--green peppers\n",
      "--extra cheese\n"
     ]
    }
   ],
   "source": [
    "# 设计一个对顾客点披萨进行描述：\n",
    "\n",
    "def make_pizza(*toopings):\n",
    "    \"\"\"概述要制作的披萨\"\"\"\n",
    "    print(\"\\nMaking a pizza with the following toppings\")\n",
    "    for topping in toopings:\n",
    "        print(\"--\"+topping)\n",
    "\n",
    "make_pizza(\"peperoni\")\n",
    "make_pizza(\"mushroom\",\"green peppers\",\"extra cheese\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Making a 14-inch pizza with the following toppings\n",
      "--peperoni\n",
      "\n",
      "Making a 12-inch pizza with the following toppings\n",
      "--mushroom\n",
      "--green peppers\n",
      "--extra cheese\n"
     ]
    }
   ],
   "source": [
    "# 结合位置实参和任意数量实参：\n",
    "\n",
    "def make_pizza(size,*toopings):  #回顾位置实参应放在前面\n",
    "    \"\"\"概述要制作的披萨\"\"\"\n",
    "    print(\"\\nMaking a \"+str(size)+\"-inch pizza with the following toppings\")\n",
    "    for topping in toopings:\n",
    "        print(\"--\"+topping)\n",
    "\n",
    "make_pizza(14,\"peperoni\")\n",
    "make_pizza(12,\"mushroom\",\"green peppers\",\"extra cheese\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 函数与模块\n",
    "- 函数的优点之一是将代码与主程序分离；\n",
    "- 我们可以更进一步，将函数存储在被称为“模块”的独立文件中，再将模块导入主程序；\n",
    "- import语句允许我们在当前运行的程序文件中使用模块中的代码。\n",
    "\n",
    "**优势：**\n",
    "\n",
    "1.通过将函数存储在独立的文件中，可隐藏程序代码的细节，将重点放在程序的高层逻辑上；\n",
    "\n",
    "2.可以让不同的程序中重用函数；\n",
    "\n",
    "3.可与其他程序员共享这些文件而不是整个程序；\n",
    "\n",
    "4.知道如何导入函数能让你使用其他程序员编写的函数库。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 导入整个模块\n",
    "- 模块是扩展名为.py的文件"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 导入特定的函数\n",
    "- 可以导入模块中的特定函数,如：\n",
    "```python\n",
    "from module_name import function_name\n",
    "```\n",
    "- 通过用逗号分开函数名可以同时导入多个函数：\n",
    "```python\n",
    "from module_name import function_0,function_1,function_2\n",
    "```\n",
    "- 对于前面的pizza案例，我们可以导入模块中的特定函数：\n",
    "```python\n",
    "from pizza import make_pizza\n",
    "make_pizza(16,'pepperoni')  #调用模块的函数\n",
    "make_pizza(12,\"mushroom\",\"green peppers\",\"extra cheese\")\n",
    "```\n",
    "*若使用此种方法，调用函数时不需要用句点。*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 使用as 给函数指定别名\n",
    "- 我们可以指定函数的另一个名称，类似于外号。\n",
    "\n",
    "**通用语法格式：**\n",
    "```python\n",
    "from moudle_name import function_name as fn\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 使用as给模块指定别名\n",
    "**通用语法格式:**\n",
    "```python\n",
    "import moudle_name as mn\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 导入模块中的所有函数\n",
    "- 使用星号（*）运算符可以让Python导入模块中的所有函数：\n",
    "\n",
    "```python\n",
    "from pizza import*\n",
    " \n",
    "make_pizza(16,'pepperoni')\n",
    "make_pizza(12,\"mushroom\",\"green peppers\",\"extra cheese\")\n",
    "```\n",
    "\n",
    "**通用语法格式:**\n",
    "\n",
    "```python\n",
    "from moudle_name import *\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 函数补充\n",
    "##### 函数引用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function search4letters in module __main__:\n",
      "\n",
      "search4letters(phrase: str, letters: str) -> set\n",
      "    return a set of the 'letters' found in 'phrase'.\n",
      "\n",
      "from search4letters\n",
      "{'e', 'i'}\n",
      "from search4letters\n",
      "{'x', 'y'}\n"
     ]
    }
   ],
   "source": [
    "def search4letters(phrase:str,letters:str)->set:\n",
    "    \"\"\"return a set of the 'letters' found in 'phrase'. \"\"\"\n",
    "    logger(\"search4letters\")\n",
    "    return set(letters).intersection(set(phrase))\n",
    "\n",
    "def logger(source):\n",
    "    print(\"from %s\"%source)\n",
    "help(search4letters)\n",
    "\n",
    "print(search4letters('hitch-hiker','aeiou'))\n",
    "print(search4letters('galaxy','xyz'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 局部变量与全局变量以及其作用域："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "before change xiaoyan 中山大学南方学院\n",
      "after change Xiaoyan\n",
      "xiaoyan 中山大学\n"
     ]
    }
   ],
   "source": [
    "school = \"中山大学\"\n",
    "\n",
    "def change_name(name:str):\n",
    "    \"\"\"修改名字\"\"\"\n",
    "    # global school\n",
    "    school = \"中山大学南方学院\"\n",
    "    print(\"before change\",name,school)\n",
    "    name = name.title()         #局部变量，可以理解这个函数就是这个变量的作用域\n",
    "    # age = 18\n",
    "    print(\"after change\",name)\n",
    "\n",
    "# print(\"age\",age)\n",
    "name = \"xiaoyan\"\n",
    "change_name(name)\n",
    "print(name,school)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 递归：\n",
    "- 递归特性：\n",
    "\n",
    "1.必须有一个明确的结束条件\n",
    "\n",
    "2.每次进入更深一层递归时，问题规模相比上次递归应有所减少。\n",
    "\n",
    "3.递归效率不高，递归次数过多会导致栈溢出（在计算机中，函数调用是通过栈（stack）这种数据结构实现的，每当进入一个函数调用，栈就会多加一层栈帧，每当函数返回，栈就会减少一层栈帧。由于栈的大小不是无限的，所以，递归调用的次数过多，会导致栈溢出。）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "5\n",
      "2\n",
      "1\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def calc(n):\n",
    "    print(n)\n",
    "    if int(n/2) == 0:\n",
    "        return n\n",
    "    return calc(int(n/2))\n",
    "\n",
    "calc(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 知识点掌握程度"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "python_base={\n",
    "       \"IDE\":{  \n",
    "               \"IDLE\":[\"操作，100（92）\",\"意义、100（90）\"],\n",
    "               \"JUPYTE\":[\"操作，100（94）\",\"意义、100（90）\"],\n",
    "               \"pycharm\":[\"操作，100（88）\",\"意义、100（86）\"],\n",
    "               \"for循环\":[\"操作，100（88）\",\"意义、100（88）\"]\n",
    "               \"while循环\":[\"操作，100（88）\",\"意义、100（88）\"]\n",
    "               \"字典\":[\"操作，100（86）\",\"意义、100（85）\"],\n",
    "               \"列表\":[\"操作，100（86）\",\"意义、100（85）\"],\n",
    "               \"函数\":[\"操作，100（85）\",\"意义、100（85）\"]\n",
    "               \n",
    "                     }\n",
    "              }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "232.188px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
